<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.gxgyl.com All rights reserved.

// +----------------------------------------------------------------------
// | Author: Liuyu
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\shiyao;

use app\common\model\shiyao\Crc as CrcModel;
use app\common\model\store\Setting as SettingModel;
use think\facade\Db;

/**
 * 申办方模型
 * Class StoreUser
 * @package app\store\model
 */
class Crc extends CrcModel {

	/**
	 * 获取用户列表
	 * @param array $param
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getList($param = []) {
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['search' => '', 'betweenTime' => []]);
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}

		// 关键词搜索
		!empty($params['search']) && $query->where('center.center_name|p.project_name|c.company_name|p.project_code', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('crc')
			->join('shiyao_project_center center', 'center.id=crc.center_id')
			->join('shiyao_project p', 'p.project_id=crc.project_id')
			->join('shiyao_company c', 'c.company_id=p.company_id')
			->where('crc.user_id', '=', $params['userId'])
			->where('crc.is_delete', '=', 0)
			->field('crc.*,p.*,c.*,center.center_name,center.center_code,center.create_time,center.pm_id')
			->order(['center.create_time' => 'desc'])
			->paginate(15)->each(function ($item, $key) {

			$item['pms'] = Db::name('shiyao_project_center_pm')->alias('pm')
				->join('user', 'user.user_id=pm.pm_id')
				->where('pm.center_id', $item['center_id'])
				->field('user.*')->select()->toArray();
			$item['pi'] = Db::name('shiyao_project_center_pi')->alias('pi')
				->join('user', 'user.user_id=pi.user_id')
				->where('pi.center_id', $item['center_id'])
				->field('user.nick_name,user.mobile,pi.*')->select()->toArray();
			$item['crc'] = Db::name('shiyao_project_center_crc')->alias('crc')
				->join('user', 'user.user_id=crc.user_id')
				->where('crc.center_id', $item['center_id'])
				->field('user.nick_name,user.mobile,crc.*')->select()->toArray();

			$item['pm'] = Db::name('user')->where('user_id', $item['pm_id'])->find();
			$item['testee_count'] = Db::name('shiyao_project_center_testee')
				->where('center_id', $item['center_id'])->count();
			$item['buzhu_count'] = Db::name('shiyao_project_pay_log')
				->where('center_id', $item['center_id'])->count();
			return $item;
		});

		return $list;
	}

	public function getListAll($param = []) {
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['search' => '', 'betweenTime' => []]);
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}

		// 关键词搜索
		!empty($params['search']) && $query->where('center.center_name|p.project_name|c.company_name|p.project_code', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('crc')
			->join('shiyao_project_center center', 'center.id=crc.center_id')
			->join('shiyao_project p', 'p.project_id=crc.project_id')
			->join('shiyao_company c', 'c.company_id=p.company_id')
			->where('crc.user_id', '=', $params['userId'])
			->where('crc.is_delete', '=', 0)
			->field('crc.*,p.*,c.*,center.center_name,center.center_code,center.create_time,center.pm_id')
			->order(['center.create_time' => 'desc'])
			->select()->toArray();

		foreach ($list as &$item) {
			$item['pms'] = Db::name('shiyao_project_center_pm')->alias('pm')
				->join('user', 'user.user_id=pm.pm_id')
				->where('pm.center_id', $item['center_id'])
				->field('user.nick_name,user.mobile')->select()->toArray();
			$item['pi'] = Db::name('shiyao_project_center_pi')->alias('pi')
				->join('user', 'user.user_id=pi.user_id')
				->where('pi.center_id', $item['center_id'])
				->field('user.nick_name,user.mobile,pi.*')->select()->toArray();
			$item['crc'] = Db::name('shiyao_project_center_crc')->alias('crc')
				->join('user', 'user.user_id=crc.user_id')
				->where('crc.center_id', $item['center_id'])
				->field('user.nick_name,user.mobile,crc.*')->select()->toArray();

			$item['pm'] = Db::name('user')->where('user_id', $item['pm_id'])->field('mobile,nick_name')->find();
			$item['testee_count'] = Db::name('shiyao_project_center_testee')
				->where('center_id', $item['center_id'])->count();
			$item['buzhu_count'] = Db::name('shiyao_project_pay_log')
				->where('center_id', $item['center_id'])->count();
		}

		return $list;
	}

	/**
	 * 批量写入
	 * @param int $goodsId
	 * @param array $specList
	 * @return array|false
	 */
	public static function increased(int $centerId, $projectId, array $crcList) {
		$password = SettingModel::getItem('trade', 10001)['order']['password'];

		Db::name('shiyao_project_center_crc')->where('project_id', $projectId)->where('center_id', $centerId)->delete();
		$dataset = [];
		foreach ($crcList as $item) {
			//新增CRc
			$userInfo = Db::name('user')->where('mobile', $item['phone'])->find();
			if ($userInfo) {
				$userId = $userInfo['user_id'];
				$userData['nick_name'] = $item['name'];
				$userData['grade_id'] = 1;
				$userData['is_delete'] = 0;
				Db::name('user')->where('user_id', $userId)->update($userData);
			} else {
				$userData['nick_name'] = $item['name'];
				$userData['mobile'] = $item['phone'];
				$userData['password'] = $password;
				$userData['grade_id'] = 1;
				$userData['create_time'] = time();
				$userData['store_id'] = self::$storeId;
				$userId = Db::name('user')->insertGetId($userData);
			}

			$data = array_merge($item, [
				'center_id' => $centerId,
				'user_id' => $userId,
				'project_id' => $projectId,
				'store_id' => self::$storeId,
			]);

			$dataset[] = $data;
		}

		return (new static )->addAll($dataset);
	}

	public static function updates(int $centerId, $projectId, array $crcList) {
		$password = SettingModel::getItem('trade', 10001)['order']['password'];
		$dataset = [];
		foreach ($crcList as $item) {

			unset($item['pay']);
			unset($item['index']);
			//新增CRc
			$userInfo = Db::name('user')->where('mobile', $item['phone'])->find();
			if ($userInfo) {
				$userId = $userInfo['user_id'];
			} else {
				$userData['nick_name'] = $item['name'];
				$userData['mobile'] = $item['phone'];
				$userData['password'] = $password;
				$userData['grade_id'] = 1;
				$userData['create_time'] = time();
				$userData['store_id'] = self::$storeId;
				$userId = Db::name('user')->insertGetId($userData);
			}
			$crc = Db::name('shiyao_project_center_crc')
				->where('center_id', $centerId)
				->where('phone', $item['phone'])->find();
			if ($crc) {
				Db::name('shiyao_project_center_crc')->where('crc_id', $crc['crc_id'])->update($item);

			} else {
				$data = array_merge($item, [
					'center_id' => $centerId,
					'user_id' => $userId,
					'project_id' => $projectId,
					'store_id' => self::$storeId,
				]);

				$dataset[] = $data;

			}

		}
		(new static )->addAll($dataset);

		return true;
	}

	/**
	 * 新增记录
	 * @param array $data
	 * @return bool
	 */
	public function add(array $data) {

		$data['store_id'] = self::$storeId;

		// 事务处理
		$this->transaction(function () use ($data) {
			// 新增
			$this->save($data);

		});
		return true;
	}

	/**
	 * 更新记录
	 * @param array $data
	 * @return bool
	 */
	public function edit(array $data) {

		$this->transaction(function () use ($data) {
			// 更新记录
			$this->save($data);

		});
		return true;
	}

	public function audit(array $data) {

		$this->transaction(function () use ($data) {
			// 更新记录
			$this->save($data);

		});
		return true;
	}

	/**
	 * 软删除
	 * @return false|int
	 */
	public function setDelete() {

		return $this->transaction(function () {
			// 删除对应的角色关系
			UserRole::deleteAll([['store_user_id', '=', (int) $this['store_user_id']]]);
			return $this->save(['is_delete' => 1]);
		});
	}
	public static function detail(int $projectId) {

		$detail = self::get(['project_id' => $projectId]);

		return $detail;
	}

}
